<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button @click="showAddCateDialog" type="primary">添加分类
          </el-button>
        </el-col>
      </el-row>
      <!-- 树形表格 -->
      <template>
        <div>
          <el-table :data="cateList" style="width: 100%"
            v-loading="loading" row-key="cat_id"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            stripe border>
            <el-table-column type="index" label="#" width="80px">
            </el-table-column>
            <!-- 商品名称 -->
            <el-table-column label="商品名称" prop="cat_name"
              min-width="100px">
            </el-table-column>
            <!-- 是否有效 -->
            <el-table-column label="是否有效" prop="cat_deleted">
              <template v-slot="scope">
                <i style="color:lightgreen;" class="el-icon-success"
                  v-if="scope.row.cat_deleted === false"></i>
                <i style="color:lightgreen;" class="el-icon-error"
                  v-else></i>
              </template>
            </el-table-column>
            <!-- 排序 -->
            <el-table-column label="排序" prop="cat_level">
              <template v-slot="scope">
                <el-tag size="mini" v-if="scope.row.cat_level === 0">
                  一级
                </el-tag>
                <el-tag type="success" size="mini"
                  v-else-if="scope.row.cat_level === 1">二级
                </el-tag>
                <el-tag type="warning" size="mini" v-else>三级
                </el-tag>
              </template>
            </el-table-column>
            <!-- 操作 -->
            <el-table-column label="操作" min-width="180px">
              <template v-slot="scope">
                <el-button type="primary" icon="el-icon-edit"
                  size="mini"
                  @click="showEditCateDialog(scope.row.cat_id)">
                  编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete"
                  size="mini"
                  @click="removeCateById(scope.row.cat_id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[5, 7, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog title="添加分类" :visible.sync="addCateDialogVisible"
      width="50%" @close="addCateDialogClosed">
      <!-- 添加分类的表单 -->
      <el-form :model="addCateForm" :rules="addCateFormRules"
        ref="addCateFormRef" label-width="100px">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name">
          </el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <el-cascader :options="parentCateList"
            :props="cascaderProps" v-model="selectedKeys"
            @change="parentCateChanged" clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消
        </el-button>
        <el-button type="primary" @click="addCate">确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类对话框 -->
    <el-dialog title="编辑分类" :visible.sync="editCateDialogVisible"
      width="50%" @close="editCateDialogClosed">
      <el-form :model="editCateForm" :rules="eidtCateFormRules"
        ref="editCateFormRef" label-width="100px">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="editCateForm.cat_name">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取
          消</el-button>
        <el-button type="primary" @click="editCateInfo">确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //商品分类的数据列表
      cateList: [],
      data: [],
      //查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      //总数据条数
      total: 0,
      //为table指定列的定义
      columns: [
        {
          label: '商品名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt',
          minWidth: '180px'
        }
      ],
      //   控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,
      addCateForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      addCateFormRules: {
        cat_name: [
          {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          },
          {
            mein: 3,
            max: 10,
            message: '分类名称的长度在3到10个字符之间',
            trigger: 'blur'
          }
        ]
        // cat_pid: [],
        // cat_level: []
      },
      //   父级分类的列表
      parentCateList: [],
      //   指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true
      },
      //   选中的父级分类的id数组
      selectedKeys: [],
      editCateDialogVisible: false,
      editCateForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      eidtCateFormRules: {
        cat_name: [
          {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          },
          {
            mein: 3,
            max: 10,
            message: '分类名称的长度在3到10个字符之间',
            trigger: 'blur'
          }
        ]
      },
      id: 1000,
      loading: true
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取商品分类的数据列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败！')
      }
      this.cateList = res.data.result
      this.total = res.data.total
      this.data = res.data.result
      this.loading = false
    },
    // 监听pagesize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    // 监听pagenum（页码）的改变事件
    handleCurrentChange(pageNum) {
      this.queryInfo.pagenum = pageNum
      this.getCateList()
    },
    //控制添加分类对话框的展示与否
    showAddCateDialog() {
      this.getParentCateList()
      this.addCateDialogVisible = true
    },
    // 获取父级分类的数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类数据失败！')
      }
      this.parentCateList = res.data
    },
    // 监听选择项变化
    parentCateChanged() {
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        this.addCateForm.cat_level = this.selectedKeys.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 点击按钮添加分类
    addCate() {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          'categories',
          this.addCateForm
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败！')
        }
        this.$message.success('添加分类成功！')
        this.getCateList()
        this.addCateDialogVisible = false
      })
    },
    // 监听添加分类的关闭
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
      this.addCateDialogVisible = false
    },
    // 展示编辑分类对话框
    async showEditCateDialog(id) {
      const { data: res } = await this.$http.get('categories/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询分类信息失败！')
      }
      this.editCateForm = res.data
      this.editCateDialogVisible = true
    },
    // 监听编辑分类对话框的关闭事件
    editCateDialogClosed() {
      this.$refs.editCateFormRef.resetFields()
    },
    // 提交编辑分类信息
    editCateInfo() {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'categories/' + this.editCateForm.cat_id,
          {
            cat_name: this.editCateForm.cat_name
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('编辑分类信息失败！')
        }
        this.getCateList()
        this.editCateDialogVisible = false
        this.$message.success('编辑分类信息成功！')
      })
    },
    // 删除商品分类
    async removeCateById(id) {
      var confirmRes = await this.$confirm(
        '此操作将永久删除该分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }
      ).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200)
        return this.$message.error('删除分类信息失败！')
      this.$message.success('删除分类信息成功！')
      this.getCateList()
    },
    append(data) {
      const newChild = { id: this.id++, label: 'testtest', children: [] }
      if (!data.children) {
        this.$set(data, 'children', [])
      }
      data.children.push(newChild)
    }
  }
}
</script>
<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
.el-table {
  font-size: 14px;
}
</style>